package orgs.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import orgs.example.pojo.*;
import orgs.example.service.CustomerService;
import orgs.example.service.UserService;
import orgs.example.utils.EntityToMap;
import orgs.example.utils.ThreadLocalUtil;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/customer")
@Validated
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private UserService userService;
    @Autowired
    private ThreadPoolTaskExecutor applicationTaskExecutor;


    @PostMapping("/searchroom")
    public Result<Object> searchroom(@RequestBody MeetingRoom meetingRoom){

        Date now = new Date();

        List<Reservation> lists = customerService.searchAllReservation();

        Iterator<Reservation> iterator = lists.iterator();
        while(iterator.hasNext()){
            Reservation r = iterator.next();

            Date reserveStart = r.getReserveStart();
            Date reserveEnd = r.getReserveEnd();

            Integer roomid = r.getRoomId();

            if(now.before(reserveEnd) && now.after(reserveStart) && r.getReserveStatus().equals("已支付")){
                customerService.changeRoomStatus(roomid,"使用");
            }
        }

        List<MeetingRoom> rooms = customerService.searchRoom(meetingRoom);

        return Result.success("查询成功",rooms);
    }


    @PostMapping("/searchorder")
    public Result<Object> searchorder(){

        List<Reservation> reservations = customerService.searchReservationByUserId();

        List<Map<String,Object>> lists = new ArrayList<>();

        Collections.sort(reservations, Comparator.comparing(Reservation::getReserveOrdertime,
                Comparator.nullsFirst(Comparator.naturalOrder())));

        for (Reservation r:reservations){
            Integer userId = r.getUserId();
            Integer roomId = r.getRoomId();

            String roomName = customerService.searchRoomByRoomId(roomId).getRoomName();
            String userAccount = userService.findByUserId(userId).getUserAccount();

            try {
                Map<String, Object> objectMap = EntityToMap.convertIgnoreNull(r);
                objectMap.put("roomName",roomName);
                objectMap.put("userAccount",userAccount);

                lists.add(objectMap);
            }catch (Exception e){
            }

        }


        return Result.success("查询成功",lists);
    }

    @PostMapping("/pay")
    public Result pay(@RequestBody Map<String,Object> params){

        Integer reserveId = (Integer) params.get("reserveId");
        customerService.changeReservationStatus(reserveId,"已支付");
        Reservation reservation = customerService.searchReservationByReserveId(reserveId);

        customerService.changeRoomStatus(reservation.getRoomId(),"预定");

        return Result.success("支付成功");
    }

    @PostMapping("/canunsubscribesearch")
    public Result<Object> canunsubscribesearch() throws Exception{

        List<Reservation> reservations = customerService.searchReservationByUserId();

        Iterator<Reservation> iterator = reservations.iterator();
        while(iterator.hasNext()){
            Reservation next = iterator.next();
            Date now = new Date();
            Date reserveStart = next.getReserveStart();
            if(((double)reserveStart.getTime() - now.getTime() /(1000 * 60 * 60)) < 24.0){
                iterator.remove();
            }
        }

        List<Map<String, Object>> lists = new ArrayList<>();

        for (Reservation r:reservations){
            Integer roomId = r.getRoomId();
            Integer userId = r.getUserId();
            MeetingRoom room = customerService.searchRoomByRoomId(roomId);
            User user = customerService.searchUserByUserId(userId);
            Map<String, Object> objectMap = EntityToMap.convertIgnoreNull(r);
            objectMap.put("userAccount",user.getUserAccount());
            objectMap.put("roomName",room.getRoomName());
            lists.add(objectMap);
        }

        return Result.success("查询成功",lists);
    }


    @PostMapping("unsubscribe")
    public Result unsubscribe(@RequestBody Map<String,Object> params){
        Integer reserveId = (Integer) params.get("reserveId");

        List<Cancellation> cancellationList = customerService.searchCancellationByRserveId(reserveId);
        for (Cancellation c:cancellationList){
            if(c.getCancelStatus().equals("待审核")){
                return Result.error("管理员未审核，禁止重复提交");
            }
        }

        Cancellation cancellation = new Cancellation();

        cancellation.setReserveId(reserveId);
        cancellation.setCancelStatus("待审核");
        cancellation.setCancelOrdertime(new Date());

        Date now = new Date();
        Reservation reservation = customerService.searchReservationByReserveId(reserveId);
        Double reserveCost = reservation.getReserveCost();
        Date reserveStart = reservation.getReserveStart();
        Integer Time = (int)((reserveStart.getTime() - now.getTime()) / (1000 * 60 * 60));
        if(Time < 24){
            return Result.error("小于24小时无法退订");
        }
        if(Time < 48){
            double returnCost = reserveCost * 0.25;
            cancellation.setCancelAmount(returnCost);
        }
        else if(Time < 72){
            double returnCost = reserveCost * 0.75;
            cancellation.setCancelAmount(returnCost);
        }else{
            cancellation.setCancelAmount(reserveCost);
        }


        customerService.addCancellation(cancellation);


        return Result.success("退订申请成功");
    }

    @PostMapping("/unsubscribesearch")
    public Result<Object> unsubscribesearch() throws Exception{

        List<Map<String,Object>> lists =customerService.searchCancellationByUserId();


        return Result.success("查询成功",lists);
    }

    public  boolean isAfter9PM() {
        // 1. 获取系统默认时区的时钟
        Clock clock = Clock.systemDefaultZone();
        // 2. 获取当前时刻的 Instant
        Instant instant = clock.instant();
        // 3. 获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        // 4. 将 Instant 转换为 ZonedDateTime
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
        // 5. 获取当前的本地时间
        LocalTime currentTime = zonedDateTime.toLocalTime();
        // 6. 创建表示当天晚上9点的时间对象
        LocalTime ninePM = LocalTime.of(21, 0);
        // 7. 比较当前时间是否晚于或等于晚上9点
        return currentTime.isAfter(ninePM) || currentTime.equals(ninePM);
    }

    @PostMapping("/findroomtime")
    public Result<Object> findroomtime(@RequestBody Map<String,Object> params) throws Exception{

        Integer roomId = (Integer) params.get("roomId");

        List<Reservation> reservations= customerService.searchAllReservationByRoomId(roomId);

        Iterator<Reservation> iterator = reservations.iterator();

        while(iterator.hasNext()){

            Reservation next = iterator.next();
            List<Cancellation> cancellations = customerService.searchCancellationByRserveId(next.getReserveId());
            for (Cancellation c:cancellations){
                if(c.getCancelStatus().equals("已退款")){
                    iterator.remove();
                    break;
                }
            }

        }

        LocalDate today = LocalDate.now();;

        LocalDateTime now = LocalDateTime.now();

        if(isAfter9PM()) {
            today = today.plusDays(1);

        }
        ArrayList<Map<String,Object>> obMap = new ArrayList<>();

        for(int i = 0;i < 61;i++){

            Map<String,Object> today_map = new HashMap<>();

            List<Integer> occ = new ArrayList<>();

            for(int j =0;j<13;j++){
                occ.add(0);
            }

            DateTimeFormatter customFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            String today_ = today.format(customFormatter1);

            today_map.put("YMD",today_);

            LocalDateTime baseTimeForSlots = LocalDateTime.of(today, LocalTime.of(8, 0));

            for (int j = 0; j < 13; j++){

                LocalDateTime slotStartTime = baseTimeForSlots.plusHours(j);
                LocalDateTime slotEndTime = baseTimeForSlots.plusHours(j + 1);

                int potentialStatusIfBooked = 2 ;


//                if (slotStartTime.isAfter(now)) {
//                    // 如果时间段的开始时间在当前时间之前或等于，那么即使有订单，它也已经是过去的订单了
//                    potentialStatusIfBooked = 2;
//                } else {
//                    // 如果时间段的开始时间在当前时间之后当前时间，那么有订单就是未来的订单
//                    potentialStatusIfBooked = 1;
//                }

                boolean isSlotBooked = false;

                for (Reservation res : reservations) {
                    Date resStart = res.getReserveStart();
                    Date resEnd = res.getReserveEnd();// 假设订单的结束时间是Exclusive（不包含该时间点）
                    LocalDateTime start = resStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                    LocalDateTime end = resEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

                    if ((start.isBefore(slotEndTime) ||start.isEqual(slotEndTime)) && (end.isAfter(slotStartTime) || end.isEqual(slotStartTime))) {
                        isSlotBooked = true; // 找到了一个重叠的订单！
                        break; // 对于当前时间段，只要找到一个订单重叠就行了，不用再检查其他订单了
                    }
                }

                if (isSlotBooked) {
                    occ.set(j, potentialStatusIfBooked);
                }

                if(slotEndTime.isBefore(now) || (slotStartTime.isBefore(now) && slotEndTime.isAfter(now))){
                    occ.set(j,1);
                }

            }

            today_map.put("HMS",occ);

            today = today.plusDays(1);

            obMap.add(today_map);

        }


        return Result.success("查询成功",obMap);

    }


    @PostMapping("/bookroom")
    public Result bookroom(@RequestBody Reservation reservation){

        if(reservation.getReserveStart() == null || reservation.getReserveStart().equals("")){
            return Result.error("预订错误");
        }

        Date now = new Date();

        reservation.setReserveOrdertime(now);
        Integer roomId = reservation.getRoomId();

        MeetingRoom meetingRoom = customerService.searchRoomByRoomId(roomId);
        customerService.changeRoomStatus(meetingRoom.getRoomId(),"锁定");

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("userId");

        reservation.setUserId(id);

        reservation.setReserveStatus("待支付");

        reservation.setReserveDeadline(new Date(now.getTime() + (30 * 60 * 1000)));

        customerService.addReservation(reservation);

        return Result.success("预定成功");

    }


}
